package cn.credit.loan.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.credit.loan.entity.Level;
import cn.credit.loan.entity.User;
import cn.credit.loan.service.level.LevelService;
import cn.credit.loan.service.user.UserService;
/**
 * 用户登录控制器类
 * @author
 *
 */
@Controller
public class UserController {
	//日志输出
	private Logger logger = Logger.getLogger(UserController.class);
	
	//注入
	@Autowired
	private UserService userService;
	
	/**
	 * 账户设置
	 * @return
	 */
	@RequestMapping("/setting")
	public ModelAndView setting(){
		return new ModelAndView("front/setting");
	}
	
	
	
	/**
	 * 法律声明
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/legal")
	public ModelAndView legal() throws Exception{
		return new ModelAndView("front/legal");
	}	
	
	/**
	 * 公司简介
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/company")
	public ModelAndView company() throws Exception{
		return new ModelAndView("front/company");
	}
	
	/**
	 * 联系我们
	 * @return
	 */
	@RequestMapping("/security")
	public ModelAndView security()throws Exception{
		return new ModelAndView("front/security");
	}
	
	
	/**
	 * 我的账户中心页面
	 * @return
	 */
	@RequestMapping("/myAccount")
	public ModelAndView myaccount()throws Exception{
		return new ModelAndView("front/myaccount");
	}
	
	
	/**
	 * 用户登录
	 * @param userphone
	 * @param userPassword
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String login(@RequestParam("userphone")String userphone,
					    @RequestParam("userPassword")String userPassword,ModelMap model,HttpSession session){
		String error="";
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			logger.info("####--------》 userphone="+userphone);
			logger.info("####--------》 userPassword="+userPassword);
	        // 把用户名密码封装为UsernamePasswordToken对象
	        UsernamePasswordToken token = new UsernamePasswordToken(userphone.trim(), userPassword.trim());
	        // RememberMe 记住我属性
	        token.setRememberMe(true);
	        try {
	            //执行登录
	            currentUser.login(token);
	        }
	        catch (UnknownAccountException e) {
	        	error="账号不存在";
	        	model.put("phonemessage", error);
	        	logger.info("###------>>"+error);
	        	e.printStackTrace();
	        	return "front/uselogin";
			}
	        catch (IncorrectCredentialsException e) {
	        	error="密码不正确";
	        	model.put("pwdmessage", error);
	        	logger.info("###------>>"+error);
	        	e.printStackTrace();
	        	return "front/uselogin";
			}
	        // 所有认证时异常的父类.
	        catch (AuthenticationException e) {
	        	error="未知错误";
	        	model.put("errormessage", error);
	        	logger.info("###------>>"+error);
	        	e.printStackTrace();
	        	return "front/uselogin";
	        }
	    }
		//从shiro的session中取Useree
		//取身份信息
		User user = (User) currentUser.getPrincipal();
		//通过map传到页面
		session.setAttribute("user", user);
		return "front/home";
	}
	
	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping(value="/logout")
	public String logout(HttpSession session){
		session.removeAttribute("user");
		logger.info("####--------》 你已退出登录");
		
		return "redirect:/home";
	}
	/**
	 * 用户注册
	 * @param user
	 * @return
	 */
	@RequestMapping("/adduser")
	@ResponseBody
	public Object addUserdata(User user){
		Map<String, Object> result=new HashMap<String,Object>();
		try {
			result.put("returnType",userService.addUser(user));
		} catch (Exception e) {
			logger.info("####---------->> 客户注册账号有误");
			e.printStackTrace();
		}
		return JSONArray.toJSONString(result);
	}
	
	/**
	 * 修改用户登录
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/updatebyuser")
	public Object updateUser(User user){
		Map<String,Object> resutl=new HashMap<String,Object>();
		/*user.setUserId(6);
		user.setUserPassword("121212");
		user.setUserName("");*/
		logger.info(user.getUserPassword());
		try {
			if(userService.updateUserBypwd(user)){
				return "index";
			}
			resutl.put("returnType", "修改成功");
		} catch (Exception e) {
			logger.info("####------> 出现错误");
			e.printStackTrace();
		}
		return resutl;
	}

	
	@Autowired
	private LevelService levelService;
	@RequestMapping(value="/getlevel")
	@ResponseBody
	public Object level_list(Level level){
		List<Level> level_list=levelService.getlevelList(level);
		for (Level level2 : level_list) {
			logger.info("####------->>"+level2.getLevelName());
		}
		return level_list;
	}
	
	
	
	

	/**
	 * 用户删除
	 * @param userId
	 * @param model
	 * @return
	 */
	@RequestMapping("/deleteuser")
	public String deleteUser(int userId,ModelMap model) {
		try {
			boolean	userIds = userService.deleteUser(userId);
			if(userIds) {
				model.addAttribute("userId", userId);
				return "UserDelete";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	
	
	/**
	 * 短信验证接口
	 */
	@RequestMapping(value = "/phone", method = RequestMethod.POST)
	public String phoneTest() throws Exception{
		//设置超时时间-可自行调整
	    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	    //初始化ascClient需要的几个参数
	    final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
	    final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
	    //替换成你的AK
	    final String accessKeyId = "LTAInEfAaHbnEU6x";//你的accessKeyId,参考本文档步骤2
	    final String accessKeySecret = "TTPQQKj6Dqz5Hs52NuiVivWidPOo4c";//你的accessKeySecret，参考本文档步骤2
	    //初始化ascClient,暂时不支持多region（请勿修改）
	    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
	            accessKeySecret);
	    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	    IAcsClient acsClient = new DefaultAcsClient(profile);
	    //组装请求对象
	    SendSmsRequest request = new SendSmsRequest();
	    //使用post提交
	    request.setMethod(MethodType.POST);
	    //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
	    request.setPhoneNumbers("13536671848");      //发送的手机号码
	    //必填:短信签名-可在短信控制台中找到
	    request.setSignName("刘宇轩");    //这个签名必须是固定的，如果你要改，你就要和我说，我帮你申请，不能乱给，不然会失败
	    //必填:短信模板-可在短信控制台中找到
	    request.setTemplateCode("SMS_133271021");  //这个内容模板必须是固定的，如果你要改，你就要和我说，我帮你申请，不能乱给，不然会失败
	    //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
	    //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
	    request.setTemplateParam("{\"code\":\"652654\"}");  //这个是往内容模板里面传递变量的参数，code就是验证码，需要你自己用随机数去生成
	    //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
	    //request.setSmsUpExtendCode("90997");
	    //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	    request.setOutId("yourOutId");
	    //请求失败这里会抛ClientException异常
	    SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
	    if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
	        //请求成功
	        System.out.println("请求成功!");
	    }
	    	return null;
	    }

}
